﻿using CBS.APP;
using CBS.Common.Office;
using CBS.DB.CBSEntity;
using CBS.Model.ManageModel;
using CBS.Model.UIModel;
using CBS.Model.ViewModel;
//using HandyControl.Controls;
using Microsoft.Win32;
using NPOI.POIFS.NIO;
using Org.BouncyCastle.Tls;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CBS.Desktop.SystemStatement
{
    /// <summary>
    /// StudentSignDetailStatement.xaml 的交互逻辑
    /// </summary>
    public partial class StudentSignDetailStatement : Window
    {
        private Pagination pager = new() { rows = 10, page = 1, sidx = nameof(StudentSignDetailStatementViewModel.CoursePlanId), sord = "desc" };

        private bool _conditionLoadState = false;

        public StudentSignDetailStatement()
        {
            InitializeComponent();

            LoadCondation();
        }

        private async void FlushGrid()
        {
            try
            {
                btn_Search.IsEnabled = false;
                btn_Export.IsEnabled = false;
                int semesterId = (SemesterSelectModel)cb_Semester.SelectedItem == null ? 0 : ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = (GradeViewModel)cb_Grade.SelectedItem == null ? 0 : ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = (ClassViewModel)cb_Class.SelectedItem == null ? 0 : ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = (CourseViewModel)cb_Course.SelectedItem == null ? 0 : ((CourseViewModel)cb_Course.SelectedItem).CourseId;
                int teacherId = (TeacherSelectModel)cb_Teacher.SelectedItem == null ? 0 : ((TeacherSelectModel)cb_Teacher.SelectedItem).TeacherId;
                string studentName = tb_Student.Text.Trim();
                string coursePlan = tb_CoursePlan.Text.Trim();

                var data = await Task.Run(() => SystemStatementApp.GetStudentSignDetailStatementList(pager, semesterId, gradeId, classId, courseId, teacherId, studentName, coursePlan));

                this.Dispatcher.Invoke(new Action(() =>
                {
                    pg_DataList.MaxPageCount = pager.total;
                    dg_Data.ItemsSource = data;
                    btn_Search.IsEnabled = true;
                    btn_Export.IsEnabled = true;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
        private async void LoadCondation()
        {
            btn_Search.IsEnabled = false;
            btn_Export.IsEnabled = false;

            // 加载 ComboBox 数据
            await LoadDataAsync();

            BindLesson();

            // 查询 Grid 数据
            //FlushGrid();

            btn_Search.IsEnabled = true;
            btn_Export.IsEnabled = true;
        }

        private async Task LoadDataAsync()
        {
            // 使用 Task.WhenAll 等待所有 ComboBox 数据加载完成
            var tasks = new List<Task>
            {
                BindSemester(),
                BindGrade(),
                BindClass(),
                BindCourse(),
                BindTeacher(),
            };

            await Task.WhenAll(tasks);
        }

        private async Task BindSemester()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => SemesterApp.GetSelectList());

                if (list.Count == 0)
                {
                    return;
                }


                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Semester.ItemsSource = list;
                    cb_Semester.SelectedIndex = 0;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async Task BindGrade()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = new List<GradeViewModel> { new GradeViewModel { GradeId = 0, GradeName = "全部" } };
                list.AddRange(await Task.Run(() => GradeApp.GetSelectList()));

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Grade.ItemsSource = list;
                    cb_Grade.SelectedIndex = 0;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindClass()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = new List<ClassViewModel> { new ClassViewModel { ClassId = 0, ClassName = "全部" } };
                list.AddRange(await Task.Run(() => ClassApp.GetSelectList()));

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Class.ItemsSource = list;
                    cb_Class.SelectedIndex = 0;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindCourse()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = new List<CourseViewModel> { new CourseViewModel { CourseId = 0, CourseName = "全部" } };
                list.AddRange(await Task.Run(() => CourseApp.GetSelectList()));

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Course.ItemsSource = list;
                    cb_Course.SelectedIndex = 0;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void BindLesson()
        {
            try
            {

                _conditionLoadState = false;

                int semesterId = (SemesterSelectModel)cb_Semester.SelectedItem == null ? 0 : ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = (GradeViewModel)cb_Grade.SelectedItem == null ? 0 : ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = (ClassViewModel)cb_Class.SelectedItem == null ? 0 : ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = (CourseViewModel)cb_Course.SelectedItem == null ? 0 : ((CourseViewModel)cb_Course.SelectedItem).CourseId;

                var list = new List<LessonSelectModel> { new LessonSelectModel { LessonId = 0, LessonTime = "全部" } };
                list.AddRange(await Task.Run(() => LessonApp.GetSelectList(semesterId, gradeId, classId, courseId)));

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Lesson.ItemsSource = list;
                    cb_Lesson.SelectedIndex = 0;
                }));

                _conditionLoadState = true;

                FlushGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
        private async Task BindTeacher()
        {
            try
            {
                var list = new List<TeacherSelectModel> { new TeacherSelectModel { TeacherId = 0, TeacherName = "全部" } };
                list.AddRange(await Task.Run(() => TeacherApp.GetSelectList()));


                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Teacher.ItemsSource = list;
                    cb_Teacher.SelectedIndex = 0;
                }));
                //BindClassPlan();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void cb_Semester_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_conditionLoadState)
                return;
            BindLesson();
        }
        private void cb_Grade_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_conditionLoadState)
                return;
            BindLesson();
        }
        private void cb_Class_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_conditionLoadState)
                return;
            BindLesson();
        }
        private void cb_Course_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_conditionLoadState)
                return;
            BindLesson();
        }

        private void btn_Search_Click(object sender, RoutedEventArgs e)
        {
            pager.page = 1;
            pg_DataList.PageIndex = 1;
            FlushGrid();
        }

        private void btn_Export_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                OpenFolderDialog dialog = new OpenFolderDialog();
                var result = dialog.ShowDialog();
                if (result == true)
                {
                    ExportToFile(dialog.FolderName);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async void ExportToFile(string filePath)
        {
            try
            {
                Mouse.OverrideCursor = Cursors.Wait;

                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;
                int teacherId = ((TeacherSelectModel)cb_Teacher.SelectedItem).TeacherId;
                string studentName = tb_Student.Text.Trim();
                string coursePlan = tb_CoursePlan.Text.Trim();

                string fileName = $"{filePath}\\学生签到详情报表-{new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()}.xlsx";

                SystemStatementApp.GetStudentSignDetailStatementExcel(fileName, semesterId, gradeId, classId, courseId, teacherId, studentName, coursePlan);


                btn_Search.IsEnabled = true;
                btn_Export.IsEnabled = true;
                Mouse.OverrideCursor = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);

                btn_Search.IsEnabled = true;
                btn_Export.IsEnabled = true;
                Mouse.OverrideCursor = null;
            }

        }

        private void pg_DataList_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            pager.page = e.Info;
            FlushGrid();
        }
    }
}
